// import { TextDecoder } from 'text-encoding-utf-8'
let bluetoothOpen = false // 手机蓝牙是否打开
let bluetoothConnect = false // 设备和蓝牙是否连接
let isHaveDevice = false // 是否查找到设备
let deviceId: string | any = null // 设备id
let serviceId: string | any = null // 服务id
let notify: string | any = null // 监听uuid
const writeId = null // 写入uuid
/**
 * 获取手机蓝牙是否打开
 */
const getBluetoothState = () => {
  // 主机模式
  return new Promise((resolve, reject) => {
    uni.openBluetoothAdapter({
      mode: 'central',
      success: (r) => {
        console.log('蓝牙初始化成功', r)
        // 获取蓝牙的匹配状态
        uni.getBluetoothAdapterState({
          success: function (row) {
            console.log('蓝牙状态：', row.available)
            if (row.available) {
              bluetoothOpen = true
              resolve('suc')
            } else {
              // 请开启蓝牙
              bluetoothOpen = false
              bluetoothConnect = false
              reject(new Error('请开启蓝牙'))
            }
          },
          fail: (ee) => {
            // 请开启蓝牙
            bluetoothOpen = false
            bluetoothConnect = false
            reject(ee)
          }
        })
      },
      fail: (e) => {
        // console.log(e)
        // 请开启蓝牙
        bluetoothOpen = false
        bluetoothConnect = false
        reject(e)
      }
    })
  })
}
/**
 * 开始搜索蓝牙设备
 */
const discoveryBluetooth = (service: string) => {
  return new Promise((resolve) => {
    uni.startBluetoothDevicesDiscovery({
      // services: [service],
      success(res) {
        console.log('开始搜索')
        console.log('搜索蓝牙外围设备完成', res)
        setTimeout(() => {
          resolve('')
        }, 2000)
      },
      fail(err) {
        console.log('搜索失败')
        console.error(err)
      }
    })
  })
}
// 关闭蓝牙搜索
const stopDiscoveryBluetooth = () => {
  uni.stopBluetoothDevicesDiscovery({
    success(r) {
      console.log('停止搜索蓝牙设备', r)
    },
    fail(err) {
      console.log('停止失败')
      console.error(err)
    }
  })
}
/**
 * 获取搜索到的设备信息
 */
const getBluetoothDevices = () => {
  return new Promise((resolve, reject) => {
    uni.getBluetoothDevices({
      success(res) {
        bluetoothConnect = false
        // 过滤掉name为空或者未知设备的设备
        const devices = res.devices.filter(function (obj) {
          return obj.name !== '' && obj.name !== '未知设备'
        })
        devices &&
          devices.forEach((item) => {
            if (item.name && item.name.substring(0, 5) === 'aaaa-') {
              deviceId = item.deviceId
            }
          })
      },
      fail: function () {
        console.log('搜索蓝牙设备失败')
        bluetoothConnect = false
        reject(new Error(''))
      },
      complete: function () {
        console.log('蓝牙搜索完成')
        // 是否具有当前设备
        if (deviceId) {
          isHaveDevice = true
        } else {
          isHaveDevice = false
        }
        resolve(isHaveDevice)
      }
    })
  })
}
/**
 * 连接蓝牙
 * deviceId 蓝牙设备id
 */
const connectBluetooth = () => {
  return new Promise((resolve, reject) => {
    uni.createBLEConnection({
      deviceId, // 设备id
      success(res) {
        console.log('连接成功')
        console.log(res)
        bluetoothConnect = true
        // 蓝牙连接成功后关闭蓝牙搜索
        stopDiscoveryBluetooth()
        resolve('')
        // 获取服务id
        getServiceId()
      },
      fail(err) {
        bluetoothConnect = false
        console.log('蓝牙连接失败')
        reject(err)
      }
    })
  })
}
// 获取服务id
const getServiceId = () => {
  uni.getBLEDeviceServices({
    deviceId,
    success(res) {
      console.log('获取服务Id', res)
      const model = res.services[0]
      serviceId = model.uuid
      // 调用蓝牙监听和写入功能
      getCharacteId()
    },
    fail(err) {
      console.error(err)
    }
  })
}
// 获取蓝牙低功耗设备某个服务中所有特征
const getCharacteId = () => {
  uni.getBLEDeviceCharacteristics({
    deviceId, // 蓝牙设备id
    serviceId, // 蓝牙服务UUID
    success(res) {
      console.log('数据监听', res)
      res.characteristics.forEach((item) => {
        // 003
        if (item.properties.notify === true) {
          // 监听
          notify = item.uuid
          startNotice()
        }
        // 002
        if (item.properties.write === true) {
          // 写入
          const writeId = item.uuid
          uni.setStorageSync('writeId', item.uuid)
        }
      })
    },
    fail(err) {
      console.log('数据监听失败', err)
    }
  })
}
// 启用低功耗蓝牙设备特征值变化时的notify功能
const startNotice = () => {
  uni.notifyBLECharacteristicValueChange({
    characteristicId: notify,
    deviceId,
    serviceId,
    state: true,
    success(res) {
      console.log(res)
      // 监听低功耗蓝牙设备的特征值变化
      uni.onBLECharacteristicValueChange((result) => {
        console.log('监听低功耗蓝牙设备的特征值变化', result)
        if (result.value) {
          //   const decoder = new TextDecoder('utf-8')
          //   const data = decoder.decode(result.value)
          //   console.log('帽子返回数据', data)
        }
      })
    },
    fail(err) {
      console.error(err)
      //   uni.showToast({
      //     title: '监听失败',
      //     icon: 'error'
      //   })
    }
  })
}
// 蓝牙发送数据
const writeData = (buffer) => {
  return new Promise((resolve, reject) => {
    uni.writeBLECharacteristicValue({
      characteristicId: uni.getStorageSync('writeId'),
      deviceId,
      serviceId,
      value: buffer,
      success(res) {
        console.log('writeBLECharacteristicValue success', res)
        resolve('')
      },
      fail(err) {
        console.log('报错了', err)
        reject(err)
      }
    })
  })
}
export default {
  getBluetoothState,
  discoveryBluetooth,
  stopDiscoveryBluetooth,
  getBluetoothDevices,
  connectBluetooth,
  getServiceId,
  getCharacteId,
  startNotice,
  writeData
}
